﻿using System.Net;
using System.Windows;
using System.Windows.Controls;
using Launch.ViewModel;
using Serilog;
using ZCommon;
using ZDriver;
using Timer = System.Timers.Timer;

namespace Launch.Views.Setting;

public partial class UdpSettingView : UserControl
{
    // 所有收到的数据
    private readonly Queue<string> _allReceivedData = new();

    // 定时器,用于定时显示串口接收数据
    private readonly Timer _showReceiveDataTimer = new(1000);

    // udp驱动
    private readonly Udp_Driver _udpDriver = Singleton<Udp_Driver>.Instance();

    // 视图模型
    private readonly UdpSettingVm _vm = new();

    // 设备的ip/port
    private IPEndPoint _devIpPort;

    public UdpSettingView()
    {
        InitializeComponent();
        DataContext = _vm;

        // 定时显示接收到的原始数据
        _showReceiveDataTimer.Elapsed += (s, e) =>
        {
            if (_allReceivedData.Count > 0)
            {
                var allShowData = string.Join("\r\n", _allReceivedData);
                _vm.ReceivedData = allShowData;
            }
        };
        _showReceiveDataTimer.Start();
    }

    /// <summary>
    ///     当接收到原始串口数据时触发
    /// </summary>
    private void OnDataReceived(object sender, byte[] data)
    {
        var oneShowData = BitConverter.ToString(data).Replace("-", " ");

        _allReceivedData.Enqueue(oneShowData);
        while (_allReceivedData.Count > 20) _allReceivedData.Dequeue();
    }

    /// <summary>
    ///     点击连接按钮
    /// </summary>
    private void BtnConnect_OnClick(object sender, RoutedEventArgs e)
    {
        // 自身ip和端口
        if (_vm.SelfIp == "Any")
        {
            // 设备ip检测
            if (!IPAddress.TryParse(_vm.DevIp.Trim(), out var devAddress))
            {
                Log.Error($"设备IP地址格式不正确: {_vm.DevIp}");
                return;
            }

            _devIpPort = new IPEndPoint(devAddress, _vm.DevPort);
            _udpDriver.Open(_vm.SelfPort);
        }
        else
        {
            // 检测ip格式
            if (!IPAddress.TryParse(_vm.SelfIp.Trim(), out var selfAddr))
            {
                Log.Error($"自身IP地址格式不正确: {_vm.DevIp}");
                return;
            }

            // 设备ip检测
            if (!IPAddress.TryParse(_vm.DevIp.Trim(), out var devAddress))
            {
                Log.Error($"设备IP地址格式不正确: {_vm.DevIp}");
                return;
            }

            _devIpPort = new IPEndPoint(devAddress, _vm.DevPort);
            _udpDriver.Open(_vm.SelfIp.Trim(), _vm.SelfPort);
        }

        var msg = _udpDriver.IsOpen() ? "已连接" : "未连接";
        _vm.ConnectState = msg;
        Log.Information($"udp{msg}");
    }

    /// <summary>
    ///     点击断开连接按钮
    /// </summary>
    private void BtnDisconnect_OnClick(object sender, RoutedEventArgs e)
    {
        _udpDriver.Close();

        var msg = _udpDriver.IsOpen() ? "已连接" : "未连接";
        _vm.ConnectState = msg;
        Log.Information($"udp{msg}");
    }

    /// <summary>
    ///     点击发送数据按钮
    /// </summary>
    private async void BtnSendMsg_OnClick(object sender, RoutedEventArgs e)
    {
        if (!_udpDriver.IsOpen())
        {
            Log.Warning("udp未连接,无法发送数据");
            return;
        }
        if(TextSend.Text.Length==0)
        {
            return;
        }

        // 获得数据
        var rawData = TextSend.Text;
        await _udpDriver.Write(rawData.HexToBytes(), _devIpPort);
    }

    /// <summary>
    ///     udp接收框加载完成
    /// </summary>
    private void TextReceive_Loaded(object sender, RoutedEventArgs e)
    {
        // 连接接收数据事件
        _udpDriver.DataReceived += OnDataReceived;
    }

    /// <summary>
    ///     清除接收到的数据
    /// </summary>
    private void BtnReceiveClear_OnClick(object sender, RoutedEventArgs e)
    {
        _allReceivedData.Clear();
        _vm.ReceivedData = "";
    }
}